layui.define(["form", "table", "fault_flow"], function (exports) {
  var $ = layui.$,
    form = layui.form,
    table = layui.table,
    fault_flow = layui.fault_flow;

  var ansTimeStopWatch = new Stopwatch(updateResponseTime);
  var disTimeStopWatch = new Stopwatch(updateDealTime);

  var timeStopWatchList = [];
  // 主流程初始化
  function renderRightBar(faultId) {
    $.ajax({
      url: fault_flow("/FlowMajor/getFlowMajorAlls"),
      type: "post",
      data: {
        faultId: faultId,
      },
      contentType: "application/x-www-form-urlencoded",
      responseType: "json",
      success: function (req) {
        let data = req.rows;
        if (data != null) {
          localStorage.setItem("faultId", faultId);
          let html = "";
          let majorList = req.majorList;
          let diffList = req.diffList[0];
          $("#popRepairPlan").css("display", "none");
          // $('.flowCount span').text(req.flowCount);
          // $('.flowCount').attr({title:$('.flowCount').text((req.rows.length>0&&req.rows[0].faultContent!=null)?(req.rows[0].faultContent):'--')})

          $(".fault-type").text(
            req.rows.length > 0 && req.rows[0].faultType != null
              ? req.rows[0].faultType
              : "--"
          );

          //销毁专业流程表的计时器
          for (let index = 0; index < timeStopWatchList.length; index++) {
            const element = timeStopWatchList[index];
            element.destory();
          }
          timeStopWatchList = [];

          ansTimeStopWatch.destory();
          disTimeStopWatch.destory();

          if (diffList.ansStatu == 0) {
            ansTimeStopWatch.tempTime = diffList.ansDiff;
            $(".fault-response-time").text(ansTimeStopWatch.toString());
            ansTimeStopWatch.start();
          } else {
            $(".fault-response-time").text(
              diffList.ansDiff == "" ? "--:--" : diffList.ansDiff
            );
          }

          if (diffList.disStatu == 0) {
            disTimeStopWatch.tempTime = diffList.disDiff;
            $(".fault-deal-time").text(disTimeStopWatch.toString());
            disTimeStopWatch.start();
          } else {
            $(".fault-deal-time").text(
              diffList.disDiff == "" ? "--:--" : diffList.disDiff
            );
          }

          for (let i = 9; i < 14; i++) {
            $(".state" + i).css("background-color", "#009688");
            $(".state" + i).attr("onClick", "");
          }
          for (let i = 0; i < majorList.length; i++) {
            $(".state" + majorList[i]).attr(
              "onClick",
              "openPopUpPage('" +
                majorList[i] +
                "','" +
                $(".state" + majorList[i]).text() +
                "');"
            );
            $(".state" + majorList[i]).css("background-color", "#FF5722");
            html +=
              ' <div class="popupSection" id="popupTableSection' +
              majorList[i] +
              '">';
            html += '     <img src="./images/process.svg"/>';
            html += '     <div class="popuoTex">';
            html +=
              '         <h3 class="tableTitle"><span class="popuoTex-tableTitle_' +
              majorList[i] +
              '"></span>';
            html +=
              '             <i class="layui-icon layui-icon-close" onclick="popupTableClose(' +
              majorList[i] +
              ');"></i>';
            html += "         </h3>";
            html += '         <div class="tableStyle">';
            html += '         <h4 class="resposeTxt">' + "故障响应时间:";
            html +=
              '              <span class="resTime_' +
              majorList[i] +
              '">' +
              "</span>";
            html += "</h4>";
            html +=
              '             <table id="popupTable' +
              majorList[i] +
              '" lay-filter="popupTable' +
              majorList[i] +
              '"></table>';
            html += "         </div>";
            html += "     </div>";
            html += " </div>";
          }
          $("#popupBox").html(html);
          for (let i = 0; i < majorList.length; i++) {
            openPopUpPage(majorList[i], $(".state" + majorList[i]).text());
          }
          var rowsData = req.rows;
          console.log(rowsData);
          form.render();
          table.render({
            elem: "#p_list",
            id: "p_list",
            height: 520,
            data: rowsData,
            limit: 5,
            skin: "nob",
            cols: [
              [
                // { field: 'answerTime', title: '预计完成时间',padding:0,width:40, align: 'center', templet: generateTime },
                {
                  field: "disposeTime",
                  title: "时间",
                  width: 50,
                  align: "center",
                  templet: generateConfirmTime_Main,
                },
                {
                  field: "flowName",
                  title: "结果",
                  width: 205,
                  align: "center",
                  templet: generateFlowEvent_Main,
                },
              ],
            ],
            // page: true,
            // limit: 10,
            // limits: [5, 15, 20, 25, 30],
            // ,page: {
            //     layout: ['prev', 'page', 'next', 'skip']
            //     ,groups: 1
            //     ,first: false
            //     ,last: false

            //   }
            page: {
              groups: 5,
              first: false,
              last: false,
              layout: ["prev", "page", "next"],
            },
            text: {
              none: "暂无数据",
            },
            done: function (res, curr, count) {
              tdTitle();
            },
          });
          table.render({
            elem: "#rightTopTable",
            url: fault_flow("/faultRecord/queryImportantRecordList"), //模拟接口
            method: "post",
            async: true,
            contentType: "application/json",
            id: "rightTopTable",
            height: 170,
            where: {
              faultId: localStorage.getItem("faultId"),
            },
            parseData: function (res) {
              return {
                code: 0,
                count: res.total,
                data: res.rows,
                msg: "",
              };
            },
            limit: 3,
            skin: "nob",
            cols: [
              [
                {
                  field: "record",
                  title: "故障关键信息",
                  align: "left",
                  width: 300,
                },
              ],
            ],
            page: {
              groups: 5,
              first: false,
              last: false,
              layout: ["prev", "page", "next"],
            },
            text: {
              none: "暂无数据",
            },
            done: function (res, curr, count) {
              tdTitle();
              table.on("row(rightTopTable)", function (obj) {
                obj.tr
                  .addClass("layui-table-click")
                  .siblings()
                  .removeClass("layui-table-click");
                $(".shape").css("display", "block");
                var tabledata = table.cache["rightTopTable"]; //获取现有数据
                var html = "";
                for (i = 0; i < tabledata.length; i++) {
                  html += " <div>" + tabledata[i].record;
                  html += "         </div>";
                }
                $(".KeyInformationDetails").html(html);
              });
            },
          });
          // table.on('row(rightTopTable)',function(obj){
          //   obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
          //   $('.KeyInformationSection').css('display','block');
          //   $('.KeyInformationDetails').text(obj.data.record)
          // })
          $("th").hide(); //表头隐藏的样式
        }
      },
    });
  }
  $(".closeKeyInformation").on("click", function () {
    $(".shape").css("display", "none");
    $(".rightTopT tr").removeClass("layui-table-click");
  });
  $(".shape").on("click", function () {
    $(".shape").css("display", "none");
    $(".rightTopT tr").removeClass("layui-table-click");
  });
  //抢救方案
  window.popupRepairPlan = function (tag) {
    let reqData = {
      faultId: localStorage.getItem("faultId") + "",
      tag: tag + "",
      flowLinkId: 6,
    };
    $.ajax({
      url: fault_flow("/flowLink/queryRepairPlan"),
      type: "post",
      async: true,
      contentType: "application/x-www-form-urlencoded",
      data: {
        faultId: localStorage.getItem("faultId"),
        tag: tag,
        flowLinkId: 6,
      },
      success: function (data) {
        if (data.msg != null) {
          let html =
            ' <div class="popupSection" id="popupTableSection_RepairPlan">';
          html +=
            '     <img class="repair-plan-image" src="./images/process1.svg"/>';
          html += '     <div class="popuoTex">';
          html +=
            '         <h3 class="tableTitle"><span>' +
            getMajorConfig(tag) +
            "抢修方案</span>";
          html +=
            '             <i style="padding-right: 10px;" class="layui-icon layui-icon-close" onclick="popupTableClose(\'_RepairPlan\');"></i>';
          html += "         </h3>";
          html += '         <div class="tableStyle">';
          html += "             <p>" + data.msg + "</p>";
          html += "         </div>";
          html += "     </div>";
          html += " </div>";
          $("#popRepairPlan").html(html);
          $("#popRepairPlan").css("display", "block");
        }
      },
    });
  };
  //专业流程
  window.openPopUpPage = function (id, name) {
    $.ajax({
      url: fault_flow("/FlowMajor/getFlowMajorStatus"),
      type: "post",
      data: {
        faultId: localStorage.getItem("faultId"),
        tag: id,
      },
      contentType: "application/x-www-form-urlencoded",
      responseType: "json",
      success: function (req) {
        $(".popuoTex-tableTitle_" + id).text(name + "处理流程");
        let diffList = req.diffList[0];
        if (diffList.ansStatu == 0) {
          var majorTimer = new Stopwatch(majorResTime, diffList.ansDiff, id);
          // $(".resTime_" + id).text("故障响应时间: " + majorTimer.toString());
          majorTimer.start();
          timeStopWatchList.push(majorTimer);
          // $('.resTime_'+id).text('故障响应时间'+diffList.ansDiff)//(req.diffList.ansDiff == null||req.diffList.ansDiff == "") ? '--:--' : (req.diffList.ansDiff)
        } else {
          $(".resTime_" + id).text(diffList.ansDiff);
          //(req.diffList.ansDiff == null||req.diffList.ansDiff == "") ? '--:--' : (req.diffList.ansDiff)
          // $('.fault-response-time').text((diffList.ansDiff == null||diffList.ansDiff == "") ? '--:--' : (diffList.ansDiff));
        }
        // test.stop();
        // test.destory();
        $("#popupTableSection" + id).css("display", "block");
        console.log(req.rows);
        table.render({
          elem: "#popupTable" + id,
          height: "",
          data: req.rows,
          limit: 11,
          skin: "nob",
          cols: [
            [
              //表头
              {
                field: "disposeTime",
                title: "实际完成时间",
                width: 60,
                align: "center",
                templet: generateConfirmTime,
              },
              {
                field: "flowName",
                title: "结果",
                width: 175,
                align: "center",
                templet: generateFlowEvent,
              },
            ],
          ],
          text: {
            none: "暂无数据",
          },
          done: function (res, curr, count) {
            console.log(res);
            tdTitle();
          },
        });
        $("th").hide(); //表头隐藏的样式
      },
    });
  };
  window.popupTableClose = function (id) {
    $("#popupTableSection" + id).css("display", "none");
  };
  function tdTitle() {
    $("th").each(function (index, element) {
      $(element).attr("title", $(element).text());
    });
    $("td").each(function (index, element) {
      $(element).attr("title", $(element).text());
    });
  }
  var majorConfig = [
    {
      major: "车辆",
      major_v: "9",
    },
    {
      major: "供电",
      major_v: "10",
    },
    {
      major: "通号",
      major_v: "11",
    },
    {
      major: "工务",
      major_v: "12",
    },
    {
      major: "物后",
      major_v: "13",
    },
    {
      major: "总流程",
      major_v: "1",
    },
  ];
  function getMajorConfig(tag) {
    for (let index = 0; index < majorConfig.length; index++) {
      const element = majorConfig[index];
      if (tag == element.major_v) {
        return element.major;
      }
    }
    return "";
  }
  function generateFlowEvent(data) {
    if (data.LAY_INDEX == 1) {
      return (
        '<span class="p_content" style="color:#fff">' +
        data.faultContent +
        " </span>"
      );
    } else {
      switch (data.statu) {
        case 2:
          return (
            '<span class="p_content" style="color:#FF5722">' +
            data.flowName +
            "</span>"
          );
        case 1:
          return (
            '<span class="p_content" style="color:#fff">' +
            data.flowName +
            " </span>"
          );
        case 0:
          return (
            '<span class="p_content" style="color:grey">' +
            data.flowName +
            " </span>"
          );
      }
    }
  }
  function generateFlowEvent_Main(data) {
    let styleColor = "";
    switch (data.statu) {
      case 2:
        styleColor = "color:#FF5722";
        break;
      case 1:
        styleColor = "color:#fff";
        break;
      case 0:
        styleColor = "color:grey";
        break;
    }

    let flowName = "(" + getMajorConfig(data.tag) + ")" + data.flowName;

    if (data.LAY_INDEX == 1) {
      return (
        '<span class="p_content" style="color:#fff">' +
        data.faultContent +
        " </span>"
      );
    } else if (data.flowLinkId == 6 && data.statu != 0) {
      let clickFunc = 'onclick="popupRepairPlan(' + data.tag + ');"';
      return (
        '<span class="p_content" style="text-decoration: underline;' +
        styleColor +
        '"' +
        clickFunc +
        ">" +
        flowName +
        " </span>"
      );
    } else {
      return (
        '<span class="p_content" style="' +
        styleColor +
        '">' +
        flowName +
        "</span>"
      );
    }
  }
  // function generateTime(data) {
  //     switch (data.statu) {
  //         case 2:
  //             return '<span class="p_time" style="color:#FF5722">' + changeShowTime(data.answerTime) + '</span>';
  //         case 1:
  //             return '<span class="p_time" style="color:#48E9FF">' + changeShowTime(data.answerTime) + '</span>';
  //         case 0:
  //             return '<span class="p_time" style="color:grey">' + changeShowTime(data.answerTime) + '</span>';
  //     }
  // };
  function updateDealTime(watch) {
    $(".fault-deal-time").text(watch.toString());
  }

  function updateResponseTime(watch) {
    $(".fault-response-time").text(watch.toString());
  }

  function majorResTime(watch, id) {
    $(".resTime_" + id).text(watch.toString());
  }

  function generateConfirmTime_Main(data) {
    if (!data.disposeTime) {
      // data.disposeTime = "--:--";
      data.disposeTime = data.answerTime;
    }
    if (data.LAY_INDEX == 1) {
      return (
        '<span class="p_time" style="color:#fff">' +
        changeShowTime(data.answerTime) +
        "</span>"
      );
    }
    switch (data.statu) {
      case 2:
        return (
          '<div class="p_time" style="color:#FF5722">' +
          changeShowTime(data.answerTime) +
          "</div>" +
          '<div class="p_contime" style="color:#FF5722">' +
          changeShowTime(data.disposeTime) +
          "</div>" +
          '<div class="p_time"  style="color:#FF5722">' +
          data.subTime +
          "</div>"
        );
      case 1:
        return (
          '<div class="p_time" style="color:#48E9FF">' +
          changeShowTime(data.answerTime) +
          "</div>" +
          '<div class="p_contime" style="color:#fff">' +
          changeShowTime(data.disposeTime) +
          "</div>" +
          '<div class="p_time" style="color:#fff">' +
          data.subTime +
          "</div>"
        );
      case 0:
        return (
          '<div class="p_time" style="color:grey">' +
          changeShowTime(data.answerTime) +
          "</div>" +
          '<div class="p_contime" style="color:grey">' +
          changeShowTime(data.disposeTime) +
          "</div>" +
          '<div class="p_time" style="color:grey">' +
          data.subTime +
          "</div>"
        );
    }
  }
  function generateConfirmTime(data) {
    if (!data.disposeTime) {
      data.disposeTime = data.answerTime;
    }
    if (data.LAY_INDEX == 1) {
      return (
        '<span class="p_time" style="color:#fff">' +
        changeShowTime(data.answerTime) +
        "</span>"
      );
    }
    switch (data.statu) {
      case 2:
        return (
          '<span class="p_contime" style="color:#FF5722">' +
          changeShowTime(data.disposeTime) +
          "</span>"
        );
      case 1:
        return (
          '<span class="p_contime" style="color:#fff">' +
          changeShowTime(data.disposeTime) +
          "</span>"
        );
      case 0:
        return (
          '<span class="p_contime" style="color:grey">' +
          changeShowTime(data.disposeTime) +
          "</span>"
        );
    }
  }
  function changeShowTime(time) {
    if (time != null && time.indexOf(" ") != -1 && time.indexOf(":") != -1) {
      let h_m = time.split(" ")[1].split(":");
      return h_m[0] + ":" + h_m[1];
    }
    return time;
  }
  var obj = {
    renderRightBar: function (data) {
      renderRightBar(data);
    },
  };

  //输出接口
  exports("right_bar", obj);
});
